go to previous page   go to home page   go to next page

Answer:

The Integer.parseInt() method crashes.


Crash!

More correctly, the method throws a NumberFormatException which the Java system catches and then prints out a stack trace:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string "rats"
        at java.lang.NumberFormatException.forInputString(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at FahrenheitPanel$TempListener.actionPerformed(FahrenheitPanel.java:52)
         . . . . and so on . . . .

The proper way to deal with this problem is to use exception handling, the subject of chapters 80 and 81. Here is the actionPerformed() method modified to deal with bad user input. Look it over, but don't worry about the details until after you have read the above chapters.

  public void actionPerformed( ActionEvent evt)  
  {
    String userIn = inFahr.getText() ;
    
    try
    {
      fahrTemp = Integer.parseInt( userIn ) ;
      celsTemp = convert( fahrTemp ) ;   
      outCel.setText( celsTemp+"" );
    }
    
    catch ( Exception ex )
    {
      outCel.setText( "Re-enter F" );  
    }  
   
    repaint();   
  }

Essentially what happens is that if anything goes wrong in any of the three statements in the block following the try:

    try
    {
      fahrTemp = Integer.parseInt( userIn ) ;
      celsTemp = convert( fahrTemp ) ;   
      outCel.setText( celsTemp+"" );
    }

an exception will be "thrown" (will happen). Then the block following the catch will execute:

    catch ( Exception ex )
    {
      outCel.setText( "Re-enter F" );  
    }  

This block writes an error message to the ouput text field.


QUESTION 8:

Look at the stack trace (above). What string did the user enter, that could not be converted into an integer?